import logging

from agent.common.system import sysCommand
from agent.feature.base import Feature
from agent.common.tools import glob

logger = logging.getLogger('common')

class Alpm(Feature):
    __domain__  = "scsi_host"
    __feature__ = "alpm"
    
    def __init__(self) -> None:
        super().__init__(self.__domain__, self.__feature__)
        self.scsi_paths = glob("/sys/class/scsi_host/host*/link_power_management_policy")
        logger.info("scsi host path: {}".format(self.scsi_paths))
        if self.scsi_paths.__len__() == 0:
            raise Exception("Can not find any hosts in /sys/class/scsi_host")
        
    def set_value(self, value):
        if type(value) is not list:
            value = [value, ] * len(self.scsi_paths)
        
        if len(value) != len(self.scsi_paths):
            logger.warning("size unmatch: {} != {}".format(len(value), len(self.scsi_paths)))
            
        for val, path in zip(value, self.scsi_paths):
            sysCommand("echo '{}' > {}".format(val, path))

    def get_value(self):
        values = []
        for path in self.scsi_paths:
            val = sysCommand("cat {scsi_host}".format(scsi_host = path))
            values.append(val)
        return values


if __name__ == "__main__":
    handler = Alpm()
    
    value = handler.get_value()

    handler.set_value("medium_power")
    handler.set_value("min_power")
    
    handler.set_value(value)
    